// 练习友元的使用方式；

// 预习运算符重载的三种形式，针对Complex类对象实现+、+=、++这几个简单运算符的重载；

// 预习下标运算符[] 的重载;

// 完成昨天布置的作业。

#include <iostream>
#include <string>
#include <cstring>

using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::ostream;
using std::istream;

class Complex
{
friend Complex operator+(const Complex& lhs, const Complex& rhs);
friend Complex operator++(Complex& lhs);
friend ostream& operator<<(ostream& os, const Complex& rhs);
friend istream& operator>>(istream &is, Complex &rhs); 
public:
    Complex(double real = 0, double imagin = 0)
        : _real(real)
        , _imagin(imagin){};
    
    // 前置 ++
    Complex& operator++(){
        _real++;
        _imagin++;
        return *this;
    }

    // +=
    Complex& operator+=(const Complex& rhs){
        _real += rhs._real;
        _imagin += rhs._imagin;
        return *this;
    }


private:

    double _real;
    double _imagin;
};

// >>
istream &operator>>(istream &is, Complex &rhs){
    // 此函数应该考虑检查输入流的状态以及是否要清空输入缓冲区
    is >> rhs._real;
    is >> rhs._imagin;
    return is;
}

// +
Complex operator+(const Complex& lhs, const Complex& rhs){
    return Complex(lhs._real + rhs._real, lhs._imagin + rhs._imagin);
}

// 后置 ++
Complex operator++(Complex& lhs){
    return Complex(lhs._real++, lhs._imagin++);
}

// <<   
ostream& operator<<(ostream& os, const Complex& rhs){
    os << rhs._real << " + " << rhs._imagin << "i";
    return os;
}

#if 0
class CharArray
{
friend ostream& operator<<(ostream& os, const CharArray& arr);
public:
    CharArray()
        : _arr(new char[1] ())
        , _size(0){}
    CharArray(const char* String)
        : _arr(new char[strlen(String) + 1])
        , _size(strlen(String)){
            strcpy(_arr, String);
    }
    CharArray(const CharArray& rhs){
        delete [] _arr;
        _arr = new char[strlen(rhs._arr) + 1] ();
        _size = strlen(rhs._arr);
    }

    ~CharArray(){if(_arr){delete [] _arr; _arr = nullptr;}}

    CharArray& operator=(const CharArray& rhs){
        delete [] _arr;
        _arr = new char[strlen(rhs._arr) + 1] ();
        _size = strlen(rhs._arr);
        return *this;
    }

    const char& operator[](int idx) const{
        if(idx >= _size - 1){cout << "访问越界" << endl;static char nullchar = '\0'; return nullchar;}

        return _arr[idx];
    }
    char& operator[](int idx) {
        if(idx >= _size - 1){cout << "访问越界" << endl;static char nullchar = '\0'; return nullchar;}

        return _arr[idx];
    }

private:
    char* _arr;
    size_t _size;
};

ostream& operator<<(ostream& os, const CharArray& arr)
{
    os << arr._arr;
    return os;
}
#endif

int main(void)
{
    Complex c1(3, 4);
    cin >> c1;
    Complex c2(5, 6);

    Complex c3 = c1 + c2;
    cout << c3 << endl;
    c3.operator++();
    cout << c3 << endl;
    c3.operator+=(c2);
    cout << c3 << endl;

    // CharArray arr("hello world!!!");
    // cout << arr[1] << endl;
    // cout << arr << endl;
    
    return 0;
}